package com.ejlchina.tool.base

import android.bluetooth.BluetoothGattCharacteristic
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import com.ejlchina.tool.MainActivity
import com.ejlchina.tool.bean.BleDeviceBean
import com.ejlchina.tool.singleton.GlobalAction
import com.ejlchina.tool.util.COMMAND_ELE_LOCK_UPWARD
import com.ejlchina.tool.util.bytearray.toHexString
import com.ejlchina.tool.util.getDownwardCommand
import com.ejlchina.tool.util.getUpwardData
import com.ejlchina.tool.viewmodel.MainViewModel
import com.ejlchina.tool.viewmodel.PRIORITY_WRITE_DEFAULT
import com.huyuhui.fastble.data.BleDevice
import kotlinx.coroutines.launch

abstract class BaseBindingFragment<T : ViewBinding>(private val bindingInflater: (layoutInflater: LayoutInflater) -> T) : Fragment() {

    // Bindings
    private var _binding: T? = null

    /**
     * Binding
     */
    protected val binding get() = _binding!!

    protected val viewModelActivity : MainViewModel by activityViewModels()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        _binding = bindingInflater.invoke(inflater)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewLifecycleOwner.lifecycleScope.launch {
            launch {
                GlobalAction.notifyDataFlow.collect{ indicatorResultBean ->
                    if (lifecycle.currentState < Lifecycle.State.RESUMED) return@collect
                    handleResultCommand(indicatorResultBean.bleDevice,indicatorResultBean.resultData)

                }
            }

            launch {
                GlobalAction.writeFailureFlow.collect{

                }
            }
        }
    }

    private fun handleResultCommand(bleDevice: BleDeviceBean, commandByteArray: ByteArray){
        val commandString = commandByteArray.toHexString(false)
        val offset = if (commandString.startsWith(COMMAND_ELE_LOCK_UPWARD)) 2 else 1
        val dataByteArray = getUpwardData(commandByteArray,offset)
        whenReceiveCommand(bleDevice, commandString.substring(0,8),dataByteArray)
            if (isAdded){

            }

    }

    open fun whenReceiveCommand(bleDevice: BleDeviceBean,command: String, dataByteArray: ByteArray){}

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    fun showLoading(){
        (requireActivity() as MainActivity).showLoading()
    }

    fun dismissLoading(){
        (requireActivity() as MainActivity).dismissLoading()
    }

    fun getCommandData(bleDevice: BleDeviceBean, command: String, commandVariable: String = "",isNeedShowLoading: Boolean = true, priority: Int = PRIORITY_WRITE_DEFAULT) {
        if (isNeedShowLoading){
            showLoading()
        }
        viewModelActivity.writeByQueue(bleDevice,getDownwardCommand(bleDevice, command, commandVariable),
            continuous = false,
            isForFileUpload = false,
            priority = priority,
            writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
        )
    }

    fun setCommandData(bleDevice: BleDeviceBean, command: String, commandVariable: String,isNeedShowLoading: Boolean = true, priority: Int = PRIORITY_WRITE_DEFAULT) {
        if (isNeedShowLoading){
            showLoading()
        }
        viewModelActivity.writeByQueue(bleDevice,getDownwardCommand(bleDevice, command, commandVariable),
            continuous = false,
            isForFileUpload = false,
            priority = priority,
            writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE)
    }

}